/**
 * @description: 数据中台-任务-任务管理-新建任务
 * @author: hj
 * @update: hj(2020-01-14)
 */
import React from 'react';
import IceContainer from '@icedesign/container';
import 'moment/locale/zh-cn';
import {Button, Form, Grid, Input as NextInput, Input, Message, Radio, Select, Tab} from '@alifd/next';
import responsive from '@/request'
import styles from './index.module.scss';
import $http from '@/service/Services';
import CodeMirror from "../../../../components/CodeMirror";

const {Option} = Select;
const {TextArea} = Input;
const {Row, Col} = Grid;
let form;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;

const formItemLayout = {
    labelCol: {
        span: 6
    },
    wrapperCol: {
        span: 18
    }
};

const formItemLayoutSQl = {
    labelCol: {
        span: 0
    },
    wrapperCol: {
        span: 24
    }
};

/**
 * list
 */
class BusinessIntelligenceTaskAdd extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showModal: false,
            source: {},
            value: {},
            valueSql: {},
            id: "",
            execSql: "",
            execError: false,
            execMessage: "",
            columns: [],
            chartList: [],
            results: [],
            chartDetail: {},
            arr: [],
            parentId: null,
            businessList: [],
            datasources: [],
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            }
        };
        this.$http = $http;
        this.formChange = this.formChange.bind(this);
        this.validateAllFormField = this.validateAllFormField.bind(this);
    }


    /**
     * 执行值改变
     * @param sql
     */
    execSqlChange = (sql) => {
        this.state.value.execSql = sql;
        this.setState(
            {
                valueSql: {
                    execSql: sql
                }
            }
        )
    };

    static defaultProps = {
        value: '',
        sqlPaste: '',
    };
    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {
        const params = new URLSearchParams(this.props.location.search);
        const id = params.get("id");
        this.setState({
            id: id,
        }, () => {
            this.getBusinessList();
            this.getBusinessIntelligenceChartList();
        });
        if (id) {
            const that = this;
            this.$http.get(responsive.event.url + '/v1/taskDetail/getBusinessIntelligenceTaskDetailPageById/' + id)
                .then(function (response) {
                    const {data} = response;
                    if (data.code === 1) {
                        Message.warning(data.message ? data.message : data.data);
                    } else {
                        that.setState({
                            value: data.data,
                            valueSql: {
                                execSql: data.data.execSql
                            }
                        },()=>{
                            if (data.data.targetTableId){
                                that.changeTargetTable(data.data.targetTableId);
                            }
                        })
                    }
                })
                .catch(function (error) {
                    Message.error(error.message);
                })
        }
    };

    /**
     *获取图例的列表
     */
    getBusinessIntelligenceChartList = () => {
        const that = this;
        let urls = responsive.event.url + '/v1/intelligenceChart/getBusinessIntelligenceChartList';
        this.$http.get(urls)
            .then(function (response) {
                const {data} = response;
                const arr = data.data;
                that.setState({
                    chartList: arr
                }, () => {

                })
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    }
    /**
     * 根据id查询详情
     */
    getBusinessList = () => {
        const that = this;
        let urls = responsive.event.url + '/v1/platformBusiness/getPlatformBusinessList';
        this.$http.post(urls)
            .then(function (response) {
                const {data} = response;
                const arr = data.data;
                that.setState({
                    businessList: arr
                }, () => {
                    if (arr && arr.length > 0) {
                        that.getAllDatasourceList(arr[0].id);
                    }
                })
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };
    /**
     * 获取所有数据源列表
     */
    getAllDatasourceList = (businessId) => {
        const that = this;
        this.$http.get(responsive.event.url + '/v1/tDataSource/getAllDatasourceList/' + businessId).then(function (response) {
            const {data} = response;
            if (data.code === 1) {
                Message.warning(data.message ? data.message : data.data);
            } else {
                that.setState({
                    datasources: data.data
                })
            }
        })
            .catch(function (error) {
                Message.error(error.message);
            });
    };
    /**
     * 表的值发生改变
     * @param formValue
     */
    formChange = (formValue) => {
        this.setState({
            value: formValue
        })
    };
    /**
     * 修改数据类型
     * @param value 新的值
     * @param event 事件
     */
    changeBusiness = (value, event) => {
        this.getAllDatasourceList(value);
    };

    /**
     * 修改数据类型
     * @param value 新的值
     * @param event 事件
     */
    changeTargetTable = (value, event) => {
        const that = this;
        this.$http.get(responsive.event.url + '/v1/intelligenceChart/getBusinessIntelligenceChartById/' + value)
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    const arr = data.data.chartColumnsVOS.map(
                        o => {
                            o["_id"] = Math.random().toString(36).substring(2);
                            return o;
                        }
                    );
                    that.setState({
                        chartDetail: data.data,
                        arr: arr
                    })
                }
            })
            .catch(function (error) {
                console.error(error);
                Message.error(error.message);
            })
    };
    /**
     * 表单数据验证并且提交
     * @param values 数据值
     * @param errors 错误
     */
    validateAllFormField = (values, errors) => {
        if (errors) {
            Message.warning('请填写必要的数据.');
            return;
        }
        values["execSql"] = this.state.valueSql.execSql;
        const that = this;
        this.$http.post(responsive.responsive.url + '/v1/taskDetail/saveOrderUpdateIntelligenceTaskDetail', values)
            .then(function (response) {
                const {data} = response;
                if (data.code === 1) {
                    Message.warning(data.message ? data.message : data.data);
                } else {
                    Message.success("操作成功.");
                    that.props.history.push("/dataService/businessIntelligence/list")
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };

    /**
     * 检查数据
     * @param rule
     * @param value
     * @returns {Promise<unknown>}
     */
    userExists(rule, value) {
        return new Promise((resolve, reject) => {
            if (!value) {
                resolve();
            } else {
                setTimeout(() => {
                    if (value === "frank") {
                        reject([new Error("Sorry, this username is already exist.")]);
                    } else {
                        resolve();
                    }
                }, 500);
            }
        });
    }

    /**
     *  获取到选中部分内容，用来实现执行部分内容
     * @param cm
     */
    onCursorActivity = (cm) => {
        if (!cm.getSelection()) {
        }
    };

    /**
     * 获取表 自动补全
     */
    getTableList = () => {
        return [];
    };
    /**
     * 输入
     * @param cm
     * @param change
     * @param editor
     * @returns {Promise<void>}
     */
    onInputRead = async (cm, change, editor) => {
        const {text} = change;
        const dechars = [
            '.',
        ];
        const autocomplete = dechars.includes(text[0]);
        if (autocomplete) {
            const data = this.getTableList(); // 获取库表列表
            editor.setOption('hintOptions', {
                tables: data,
                completeSingle: false
            });
            cm.execCommand('autocomplete');
        } else {
            const tableName = this.getTableList(); // 获取表列表
            editor.setOption('hintOptions', {
                tables: tableName,
                completeSingle: false
            });
        }
        cm.execCommand('autocomplete');
    };


    /**
     * 测试
     */
    testBiSqlSelect = () => {
        const that = this;
        const {value, valueSql} = this.state;
        this.$http.post(responsive.responsive.url + '/v1/tDataSource/testBiSqlSelect', {
            sql: valueSql.execSql,
            sourceDataSourceId: value.datasourceId
        })
            .then(function (response) {
                const {data} = response;
                that.setState({
                    execError: false,
                    execMessage: "",
                    columns: data.data.columns,
                    results: data.data.result.map(o => {
                        o["_id"] = new Date().getTime();
                        return o;
                    })
                }, () => {
                    console.log(that.state.results);
                })
            })
            .catch(function (error) {
                that.setState({
                    execError: true,
                    execMessage: error.message,
                    columns: [],
                    results: []
                });
                that.forceUpdate();
            })
    }

    /**
     * 表
     * @returns {*}
     */
    render() {
        const {sqlPaste, onChange} = this.props;
        const {execError, execMessage} = this.state;
        return (
            <div>
                <div className='container-header'>
                    <p style={{display: 'inline-block'}}>{this.state.id ? "修改任务" : "新建任务"}</p>
                    <Button type="normal" size="small" className='next-btn-normal table-btn-return'
                            style={{float: 'right'}}>
                        <a onClick={() => {
                            this.props.history.go(-1)
                        }}> 返回</a>
                    </Button>
                </div>
                <Row gutter={24} style={{marginBottom: 15}}>
                    <Col span={8}>
                        <div style={{
                            border: '1px solid #f0f0f0',
                            margin: '24px',
                            fontSize: '18px',
                            minWidth: '100%',
                            width: '100%',
                        }}>
                            <IceContainer className='container-main'>
                                <Form style={{width: "90%"}}  {...formItemLayout}>
                                    <FormItem
                                        hidden={true}
                                    >
                                        <NextInput
                                            id="id"
                                            name="id"
                                            defaultValue={this.state.value.id}
                                            aria-required="true"/>
                                    </FormItem>
                                    <FormItem
                                        label="任务名称:"
                                        hasFeedback
                                        required
                                        requiredTrigger="onBlur"
                                        validator={this.userExists.bind(this)}
                                        help=""
                                        requiredMessage="任务名称不能为空"
                                    >
                                        <Input placeholder="请输入任务名称" defaultValue={this.state.value.name} name="name"/>
                                        <Form.Error name="name">
                                            {(errors, state) => {
                                                if (state === "loading") {
                                                    return "loading...";
                                                } else {
                                                    return errors;
                                                }
                                            }}
                                        </Form.Error>
                                    </FormItem>


                                    <FormItem
                                        label="业务类型:"
                                        hasFeedback
                                        required
                                        requiredTrigger="onBlur"
                                        requiredMessage="业务类型不能为空"
                                    >
                                        <Select name={'businessId'}
                                                placeholder="请选择"
                                                defaultValue={this.state.value.subjectId}
                                                className={styles.inputNme} onChange={this.changeBusiness}
                                        >
                                            {
                                                this.state.businessList.map(
                                                    o => {
                                                        return (<Option value={o.id}>{o.name}</Option>)
                                                    }
                                                )
                                            }
                                        </Select>
                                    </FormItem>

                                    <FormItem
                                        label="源数据库:"
                                        hasFeedback
                                        required
                                        requiredTrigger="onBlur"
                                        requiredMessage="源数据库不能为空"
                                    >
                                        <Select name={'datasourceId'}
                                                placeholder="请选择"
                                                onChange={(e) => {
                                                    this.state.value.datasourceId = e
                                                }}
                                                defaultValue={this.state.value.datasourceId}
                                                className={styles.inputNme}
                                        >
                                            {
                                                this.state.datasources.map(
                                                    o => {
                                                        return (<Option value={o.id}>{o.name}</Option>)
                                                    }
                                                )
                                            }
                                        </Select>
                                    </FormItem>


                                    <FormItem
                                        label="目标数据源:"
                                        hasFeedback
                                        required
                                        requiredTrigger="onBlur"
                                        requiredMessage="目标数据源不能为空"
                                    >
                                        <Select name={'targetSourceId'}
                                                placeholder="请选择"
                                                onChange={(e) => {
                                                    this.state.value.targetSourceId = e
                                                }}
                                                defaultValue={this.state.value.targetSourceId}
                                                className={styles.inputNme}
                                        >
                                            {
                                                this.state.datasources.map(
                                                    o => {
                                                        return (<Option value={o.id}>{o.name}</Option>)
                                                    }
                                                )
                                            }
                                        </Select>
                                    </FormItem>


                                    <FormItem
                                        label="执行频率:"
                                        hasFeedback
                                        required
                                        requiredTrigger="onBlur"
                                        validator={this.userExists.bind(this)}
                                        help=""
                                        requiredMessage="执行频率不能为空"
                                    >
                                        <Input placeholder="执行频率" defaultValue={this.state.value.corn} name="corn"/>
                                        <Form.Error name="corn">
                                            {(errors, state) => {
                                                if (state === "loading") {
                                                    return "loading...";
                                                } else {
                                                    return errors;
                                                }
                                            }}
                                        </Form.Error>
                                    </FormItem>


                                    <FormItem
                                        label="关联图例:"
                                        hasFeedback
                                        required
                                        requiredTrigger="onBlur"
                                        requiredMessage="关联图例不能为空"
                                    >
                                        <Select name={'targetTableId'}
                                                placeholder="请选择关联图例"
                                                defaultValue={this.state.value.targetTableId}
                                                className={styles.inputNme}
                                                onChange={this.changeTargetTable}
                                        >
                                            {
                                                this.state.chartList.map(
                                                    o => {
                                                        return (<Option value={o.id}>{o.name}</Option>)
                                                    }
                                                )
                                            }
                                        </Select>
                                    </FormItem>

                                    <FormItem
                                        label="数据持续时长:"
                                        help=""
                                        format={"number"}
                                        requiredMessage="数据持续时长不能为空"
                                    >
                                        <Input type={"number"} defaultValue={this.state.value.holdTimeout}
                                               placeholder="数据持续时长"
                                               name="holdTimeout"/>
                                    </FormItem>

                                    <FormItem
                                        label="备注:">
                                        <Input.TextArea
                                            size={'large'}
                                            rows={8}
                                            defaultValue={this.state.value.content}
                                            showLimitHint
                                            placeholder="任务备注"
                                            name="content"/>
                                    </FormItem>


                                    <FormItem
                                        label="附加条件:">
                                        <Input.TextArea showLimitHint
                                                        defaultValue={this.state.value.whereAnd} placeholder="附加条件"
                                                        name="whereAnd"/>
                                    </FormItem>


                                    <FormItem wrapperCol={{offset: 6}}>
                                        <Form.Submit
                                            validate
                                            type="primary"
                                            onClick={(v, e) => this.validateAllFormField(v, e)}
                                            style={{marginRight: 10}}
                                        >
                                            提交
                                        </Form.Submit>
                                        <Form.Reset>重置</Form.Reset>
                                    </FormItem>
                                </Form>
                            </IceContainer>
                        </div>
                    </Col>
                    <Col span={16}>
                        <div style={{
                            border: '1px solid #f0f0f0',
                            margin: '24px',
                            fontSize: '12px',
                            font: 'inherit !important',
                            fontFamily: 'Menlo,Lucida Console,Courier New,Ubuntu Mono,Consolas,source-code-pro,monospace',
                            fontVariant: 'tabular-nums',
                            lineHeight: '1.5715',
                            fontFeatureSettings: '"tnum","tnum"'
                        }}>
                            <IceContainer className='container-main'>
                                <Form   {...formItemLayoutSQl}>
                                    <FormItem
                                        requiredMessage="执行的SQL不能为空">
                                        <CodeMirror
                                            className={
                                                styles.sql
                                            }
                                            options={{
                                                readOnly: false
                                            }}
                                            value={this.state.valueSql.execSql}
                                            paste={sqlPaste}
                                            onChange={sql => {
                                                this.execSqlChange(sql);
                                            }} // sql变化事件
                                            onCursorActivity={(cm) => this.onCursorActivity(cm)} // 用来完善选中监听
                                            onInputRead={// 自动补全
                                                (cm, change, editor) => this.onInputRead(cm, change, editor)
                                            }
                                        />
                                    </FormItem>
                                    <FormItem wrapperCol={{offset: 1}}>
                                        <Button onClick={() => {
                                            this.testBiSqlSelect();
                                        }} type="normal">
                                            执行
                                        </Button>
                                    </FormItem>
                                </Form>
                                <div>
                                    <Tab>
                                        <Tab.Item title="字段关系" size="small" style={{fontSize: '12px',fontWeight: '900'}} key="1">
                                            <h4 className={styles.dTitle}>表名称:{this.state.chartDetail.tableName}</h4>
                                            <div className="el-table"
                                                 style={{overflow: 'scroll', height: '600px', width: '100%'}}>
                                                <table cellSpacing="0" style={{
                                                    width: '100%',
                                                    display: 'table',
                                                    borderCollapse: 'separate',
                                                    textIndent: 'initial',
                                                    fontSize: '12px',
                                                    overflow: 'scroll',
                                                    color: '#606266'
                                                }}>
                                                    <thead>
                                                    <tr>
                                                        <th className="is-leaf">
                                                            <div className="cell" style={{width: '200px'}}>数据列名称</div>
                                                        </th>
                                                        <th className="is-leaf">
                                                            <div className="cell" style={{width: '200px'}}>数据列</div>
                                                        </th>
                                                        <th className="is-leaf">
                                                            <div className="cell" style={{width: '200px'}}>数据列类型</div>
                                                        </th>
                                                    </tr>
                                                    </thead>
                                                    <tbody>
                                                    {
                                                        this.state.arr.map(r => {
                                                            return (
                                                                <tr>
                                                                    <td>
                                                                        <div className="cell"
                                                                             style={{width: '200px'}}>{r.columnName}</div>
                                                                    </td>
                                                                    <td>
                                                                        <div className="cell"
                                                                             style={{width: '200px'}}>{r.column}</div>
                                                                    </td>
                                                                    <td>
                                                                        <div className="cell"
                                                                             style={{width: '200px'}}>{r.columnType}</div>
                                                                    </td>
                                                                </tr>
                                                            )
                                                        })
                                                    }
                                                    </tbody>
                                                </table>
                                            </div>
                                        </Tab.Item>
                                        <Tab.Item title="结果" size="small" style={{fontSize: '12px',fontWeight: '900'}} key="2">
                                            {
                                                [0].map(oo => {
                                                    if (execError) {
                                                        return (
                                                            <Message title="执行失败" type="error">
                                                                {execMessage}
                                                            </Message>
                                                        )
                                                    } else {
                                                        if (this.state.results.length > 0) {
                                                            return (
                                                                <div className="el-table" style={{
                                                                    overflow: 'scroll',
                                                                    height: '600px',
                                                                    width: '100%'
                                                                }}>
                                                                    <table cellSpacing="0" style={{
                                                                        width: '100%',
                                                                        display: 'table',
                                                                        borderCollapse: 'separate',
                                                                        textIndent: 'initial',
                                                                        fontSize: '12px',
                                                                        overflow: 'scroll',
                                                                        color: '#606266'
                                                                    }}>
                                                                        <thead>
                                                                        <tr>
                                                                            {
                                                                                Array.isArray(this.state.columns) &&
                                                                                this.state.columns.length > 0 &&
                                                                                this.state.columns.map(c => {
                                                                                    return (
                                                                                        <th className="is-leaf">
                                                                                            <div className="cell"
                                                                                                 style={{width: '200px'}}>{c}</div>
                                                                                        </th>
                                                                                    )
                                                                                })
                                                                            }
                                                                        </tr>
                                                                        </thead>
                                                                        <tbody>
                                                                        {
                                                                            this.state.results.map(r => {
                                                                                return (
                                                                                    <tr>
                                                                                        {
                                                                                            this.state.columns.map(c => {
                                                                                                return (
                                                                                                    <td>
                                                                                                        <div
                                                                                                            className="cell"
                                                                                                            style={{width: '200px'}}>{r[c]}</div>
                                                                                                    </td>
                                                                                                )
                                                                                            })
                                                                                        }
                                                                                    </tr>
                                                                                )
                                                                            })
                                                                        }
                                                                        </tbody>
                                                                    </table>
                                                                </div>
                                                            )
                                                        } else {
                                                            return null;
                                                        }
                                                    }
                                                })
                                            }
                                        </Tab.Item>
                                    </Tab>
                                </div>
                            </IceContainer>
                        </div>
                    </Col>
                </Row>

            </div>
        );
    }

}

export default BusinessIntelligenceTaskAdd;
